/**
 * 
 */
package com.geekteam.masterenglish.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;

/**
 * @author MTROL
 *
 */
public class RESTCaller {

	public static String excute(String url){
		DefaultHttpClient httpClient = getThreadSafeClient();
		HttpGet httpGet = new HttpGet(url);
		String result = null;
		HttpEntity entity = null;
		
		try {
			HttpResponse response = httpClient.execute(httpGet);
			entity = response.getEntity();
			if (entity != null) {
				InputStream instream = entity.getContent();
				result = convertStreamToString(instream);
				/*int startSub = result.indexOf("{");
				if (startSub > 0) {
					result = result.substring(startSub);
				}*/
				instream.close();
			}
			entity.consumeContent();
			httpClient.getConnectionManager().shutdown();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			result = null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			result = null;
		} catch (IOException e) {
			e.printStackTrace();
			result = null;
		} catch (Exception ex) {
			result = null;
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		
		return result;
	}
	
	private static String convertStreamToString(InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			if ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			while ((line = reader.readLine()) != null) {
				sb.append("\n" + line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	private static DefaultHttpClient getThreadSafeClient(){
		DefaultHttpClient client = new DefaultHttpClient();
		ClientConnectionManager mgr = client.getConnectionManager();
		HttpParams params = client.getParams();
		client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
		return client;
	}
}
